﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Kiva7.Utilities;
using Kiva7.DataRequests;
using Kiva7.DataClasses;
using Kiva7.Controls;
using Microsoft.Phone.Controls.Maps;
using Kiva7.Translations;
using Kiva7.Images;
using Kiva7.Constants;

namespace Kiva7.Pages
{
    public sealed partial class LoanDetailPage
    {
        private const string Url = "/Pages/LoanDetailPage.xaml";
        public readonly static Uri PageUrl = new Uri(Url, UriKind.RelativeOrAbsolute);

        public static Uri GetPageUrl(IEnumerable<Loan> loanList, int index)
        {
            if (loanList == null)
                return null;

            List<int> list = loanList.Select(loan => loan.Id).ToList();

            UrlCreator url = new UrlCreator(Url);
            url.Add(CacheGuidKey, CacheIdList(list));
            url.Add(IndexKey, index);

            return url.ToUri(UriKind.RelativeOrAbsolute);
        }

        public LoanDetailPage()
        {
            InitializeComponent();
            CreateStandardControls();

            SetPivot(Pivot);
        }

        private void PhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {
            _request = new LoanDetailRequest();
            _request.OnResponse += request_OnResponse;

            DataContext = _request;

            _partnerRequest = new PartnerRequest();
            partnerDetailControl.DataContext = _partnerRequest;

            _journalEntriesRequest = new LenderJournalEntriesRequest();
            journalEntriesControl.DataContext = _journalEntriesRequest;

            _loanLendersRequest = new LoanLendersRequest();
            lendersControl.DataContext = _loanLendersRequest;

            RequestMain();

            ApplicationBar.IsVisible = IdList.Count > 1;
        }

        void request_OnResponse(object sender, DataRequest<DataResponse.LoansResponse, Loan>.DataRequestEventArgs e)
        {
            if (!e.Cancelled
                && e.Exception == null)
            {
                CheckPivot(Pivot.SelectedItem as PivotItem);
            }
        }

        LoanDetailRequest _request;
        protected override void RequestMain()
        {
            if (_request.LoadStatus == LoadStatus.NotLoaded)
            {
                _request.GetLoan(IdList[Index]);
            }
        }

        PartnerRequest _partnerRequest;
        private void RequestPartner()
        {
            if (_request != null
                && _request.IsLoaded
                && _request.SingleData != null
                && _partnerRequest.Partner == null)
            {
                _partnerRequest.GetPartner(_request.SingleData.PartnerId);
            }
        }

        LenderJournalEntriesRequest _journalEntriesRequest;
        private void RequestJournalEntries()
        {
            if (_journalEntriesRequest.LoadStatus == LoadStatus.NotLoaded)
            {
                LoanDetailRequest loanRequest = DataContext as LoanDetailRequest;
                if (loanRequest != null)
                {
                    Loan loan = loanRequest.SingleData;
                    if (loan != null
                        && loan.JournalTotals != null
                        && (loan.JournalTotals.Entries + loan.JournalTotals.BulkEntries) > 0)
                    {
                        _journalEntriesRequest.GetJournalEntries(loan.Id, true);
                    }
                    else
                    {
                        _journalEntriesRequest.IsLoaded = true;
                    }
                }
            }
        }

        LoanLendersRequest _loanLendersRequest;
        private void RequestLenders()
        {
            if (_loanLendersRequest.LoadStatus == LoadStatus.NotLoaded)
            {
                _loanLendersRequest.GetLenders(IdList[Index]);
            }
        }

        private void PivotLoadingPivotItem(object sender, PivotItemEventArgs e)
        {
            CheckPivot(e.Item);
        }

        protected override void CheckPivot(PivotItem pi)
        {
            if (_BarButtonSpeak != null)
            {
                _BarButtonTranslate.IsEnabled = pi == Main;
                _BarButtonSpeak.IsEnabled = pi == Main;
            }
            if (pi == Journal)
            {
                RequestJournalEntries();
            }
            else if (pi == Lenders)
            {
                RequestLenders();
            }
            else if (pi == Partner)
            {
                RequestPartner();
            }
            else if (pi == Map)
            {
                CreateMap();
            }
        }

        private Map _map; 
        private void CreateMap()
        {
            if (_request != null
                && _request.SingleData != null
                && _request.SingleData.Location != null
                && _request.SingleData.Location.Geo != null)
            {
                if (_map == null)
                {
                    _map = new Map
                        {

                            CredentialsProvider =
                                new ApplicationIdCredentialsProvider(
                                    Constant.BingMapId),
                            LogoVisibility = Visibility.Collapsed,
                            CopyrightVisibility = Visibility.Collapsed,
                            ZoomLevel = 6,
                            ZoomBarVisibility = Visibility.Collapsed,
                            Center = _request.SingleData.Location.Geo.Coordinate,
                            Mode = new AerialMode()
                        };

                    Map.Content = _map;
                }
                else
                {
                    _map.Center = _request.SingleData.Location.Geo.Coordinate;
                }
            }
        }

        protected override void ClearRequests()
        {
            _request.Clear();
            _partnerRequest.Clear();
            _journalEntriesRequest.Clear();
            _loanLendersRequest.Clear();
        }

        private BindableApplicationBarButton _BarButtonSpeak;
        private BindableApplicationBarButton _BarButtonTranslate;

        protected override void CreateApplicationBar()
        {
            AddBarButton(AppResources.Back, ImageUrls.Back, BackClick);

            _BarButtonTranslate = AddBarButton(AppResources.TranslateTexts, ImageUrls.Translation, TranslateClick);
            _BarButtonSpeak = AddBarButton(AppResources.Speak, ImageUrls.SpeachBubble, Speak);

            AddBarButton(AppResources.Next, ImageUrls.Next, NextClick);
        }

        private void TranslateClick(object sender, EventArgs e)
        {
            LoanImageControl1.TranslateTextWithDetect();
        }

        private void Speak(object sender, EventArgs e)
        {
            LoanImageControl1.Speak();
        }
    }
}